<template>
  <div class="login">
    <LoginLeftView></LoginLeftView>

    <div class="right-wrap">
      <AuthTopBar></AuthTopBar>
      <div class="header">
        <ArtLogo class="icon" />
        <h1>{{ systemName }}</h1>
      </div>
      <div class="login-wrap">
        <div class="form">
          <h3 class="title">{{ $t('login.title') }}</h3>
          <p class="sub-title">{{ $t('login.subTitle') }}</p>
          <ElForm
            ref="formRef"
            :model="formData"
            :rules="rules"
            :key="formKey"
            @keyup.enter="handleSubmit"
            style="margin-top: 25px"
          >
            <!-- <ElFormItem prop="account">
              <ElSelect v-model="formData.account" @change="setupAccount" class="account-select">
                <ElOption
                  v-for="account in accounts"
                  :key="account.key"
                  :label="account.label"
                  :value="account.key"
                >
                  <span>{{ account.label }}</span>
                </ElOption>
              </ElSelect>
            </ElFormItem> -->
            <ElFormItem prop="username">
              <ElInput
                :placeholder="$t('login.placeholder.username')"
                v-model.trim="formData.username"
              />
            </ElFormItem>
            <ElFormItem prop="password">
              <ElInput
                :placeholder="$t('login.placeholder.password')"
                v-model.trim="formData.password"
                type="password"
                radius="8px"
                autocomplete="off"
                show-password
              />
            </ElFormItem>
            <el-form-item prop="verifyCode">
              <el-input
                v-model.trim="formData.verifyCode"
                placeholder="验证码"
                type="text"
                tabindex="3"
                :prefix-icon="Key"
                maxlength="7"
                size="large"
              >
                <template #append>
                  <el-image :src="codeUrl" draggable="false" @click="createCode">
                    <template #placeholder>
                      <el-icon>
                        <Picture />
                      </el-icon>
                    </template>
                    <template #error>
                      <el-icon>
                        <Loading />
                      </el-icon>
                    </template>
                  </el-image>
                </template>
              </el-input>
            </el-form-item>

            <!-- <div class="forget-password">
              <ElCheckbox v-model="formData.rememberPassword">{{
                $t('login.rememberPwd')
              }}</ElCheckbox>
              <RouterLink :to="{ name: 'ForgetPassword' }">{{ $t('login.forgetPwd') }}</RouterLink>
            </div> -->

            <div style="margin-top: 30px">
              <ElButton
                class="login-btn"
                type="primary"
                @click="handleSubmit"
                :loading="loading"
                v-ripple
              >
                {{ $t('login.btnText') }}
              </ElButton>
            </div>

            <div class="footer">
              <p>
                {{ $t('login.noAccount') }}
                <RouterLink :to="{ name: 'Register' }">{{ $t('login.register') }}</RouterLink>
              </p>
            </div>
          </ElForm>
        </div>
      </div>
    </div>
  </div>
</template>

<script setup lang="ts">
  import AppConfig from '@/config'
  import { useUserStore } from '@/store/modules/user'
  import { useI18n } from 'vue-i18n'
  import { HttpError } from '@/utils/http/error'
  import { fetchLogin, fetchGetUserInfo, getCaptcha } from '@/api/auth'
  import { ElNotification, type FormInstance, type FormRules } from 'element-plus'
  import { onMounted } from 'vue'
  import { Key, Loading, Picture } from '@element-plus/icons-vue'
  defineOptions({ name: 'Login' })

  const { t, locale } = useI18n()
  const formKey = ref(0)
  const codeUrl = ref('')

  // 监听语言切换，重置表单
  watch(locale, () => {
    formKey.value++
  })

  const userStore = useUserStore()
  const router = useRouter()

  const systemName = AppConfig.systemInfo.name
  const formRef = ref<FormInstance>()

  const formData = reactive({
    verifyCode: '',
    username: 'admin',
    password: 'a123456',
    captchaId: '',
    rememberPassword: true
  })

  const rules = computed<FormRules>(() => ({
    username: [{ required: true, message: t('login.placeholder.username'), trigger: 'blur' }],
    password: [{ required: true, message: t('login.placeholder.password'), trigger: 'blur' }]
  }))

  const loading = ref(false)

  onMounted(() => {
    createCode()
  })

  /** 创建验证码 */
  function createCode() {
    // 清空已输入的验证码
    formData.verifyCode = ''
    // 清空验证图片
    codeUrl.value = ''
    formData.captchaId = ''
    // 获取验证码图片
    getCaptcha().then((res) => {
      console.log(res, 'res')
      codeUrl.value = res.data.img
      formData.captchaId = res.data.id
    })
  }

  // 登录
  const handleSubmit = async () => {
    if (!formRef.value) return
    try {
      // 表单验证
      const valid = await formRef.value.validate()
      if (!valid) return

      loading.value = true

      // 登录请求
      const { username, password } = formData

      const loginResponse = await fetchLogin({
        username: username,
        password,
        captchaId: formData.captchaId,
        verifyCode: formData.verifyCode
      })
      let { token } = loginResponse.data

      // 验证token
      if (!token) {
        throw new Error('Login failed - no token received')
      }

      // 存储token和用户信息
      userStore.setToken(token)
      const userInfoRes = await fetchGetUserInfo()
      console.log(userInfoRes.data, 'userInfo')
      userStore.setUserInfo(userInfoRes)
      userStore.setLoginStatus(true)

      // 登录成功处理
      showLoginSuccessNotice()
      router.push('/')
    } catch (error) {
      // 处理 HttpError
      if (error instanceof HttpError) {
        // console.log(error.code)
      } else {
        // 处理非 HttpError
        // ElMessage.error('登录失败，请稍后重试')
        console.error('[Login] Unexpected error:', error)
      }
      createCode()
    } finally {
      loading.value = false
    }
  }

  // 登录成功提示
  const showLoginSuccessNotice = () => {
    setTimeout(() => {
      ElNotification({
        title: t('login.success.title'),
        type: 'success',
        duration: 2500,
        zIndex: 10000,
        message: `${t('login.success.message')}, ${systemName}!`
      })
    }, 150)
  }
</script>

<style lang="scss" scoped>
  @use './index';
</style>
